<template>
  <div class="user-edit-container">
    <h2>{{ id ? "编辑" : "新增" }}</h2>

    <el-form ref="formRef" :model="form" label-width="100px" :rules="rules">
      <el-form-item label="任务名称" prop="taskName">
        <el-input v-model="form.taskName" />
      </el-form-item>
      <el-form-item label="所属脚本" prop="taskContent" style="height: 100%">
        <el-select
          v-model="scriptValue"
          placeholder="请选择脚本"
          style="width: 240px"
          @change="scriptValueChange()"
        >
          <el-option
            v-for="item in scriptOptions"
            :key="item.scriptId"
            :label="item.scriptName"
            :value="item.scriptId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="任务描述" prop="taskDes">
        <el-input v-model="form.taskDes" />
      </el-form-item>
      <!-- <el-form-item label="请求参数" prop="taskDes">
        <dynamicsNat
          :disabled="false"
          ref="dynamicsNatRef"
          v-model:modelValue="form.taskParam"
          v-model:newScriptId="form.scriptId"
          :scriptValue="scriptValue"
          :taskForm="form"
        ></dynamicsNat>
      </el-form-item> -->
      <!-- <el-form-item label="" prop="taskDes">
        <monacoEditor
          :taskForm="form"
          :scriptValue="scriptDataValue"
          v-show="route.params.scriptId != 'add' || scriptValue != ''"
          @runCode="runCode"
        >
        </monacoEditor>
      </el-form-item> -->

      <el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { gmtScriptinfopage, gmtScriptinfo } from "@/api/gmtScript";
import { gmtTaskinfo, gmtTaskinfosave, gmtTaskinfoUpdate } from "@/api/gmtTask";
import { ElMessage } from "element-plus";
import dynamicsNat from "./dynamicsNat.vue";
import monacoEditor from "./monacoEditor.vue";

const router = useRouter();
const route = useRoute();
const id = ref(route.params.id);
const dynamicsNatRef = ref(null);
const formRef = ref(null);
const form: any = reactive({});
const scriptValue = ref("");
const scriptDataValue = ref({});
const scriptOptions = ref();

const rules = reactive({
  name: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" },
  ],
  age: [{ required: true, message: "请输入年龄", trigger: "blur" }],
  address: [
    {
      required: true,
      message: "请输入地址",
      trigger: "blur",
      resText: "请输入",
    },
  ],
});

const queryData = ref({
  pageNum: 1,
  pageSize: 10,
  orderBy: {},
  conditions: [
    {
      column: "scriptName",
      type: "like",
      value: "",
    },
  ],
  asc: true,
});

// 如果是编辑，加载用户数据
onMounted(async () => {
  const res: any = await gmtScriptinfopage(queryData.value);
  scriptOptions.value = res.records;

  if (id.value && id.value !== "0" && id.value != "add") {
    loadUserData();
  } else {
    const mockData = {
      taskId: "",
      taskName: "",
      taskParam: "",
    };
    Object.assign(form, mockData);
  }
});

//脚本选择
const scriptValueChange = async () => {
  const scriptData: any = await gmtScriptinfo(scriptValue.value);
  scriptDataValue.value = scriptData;
  if (route.params.id == "add") {
    form.taskParam = scriptData.scriptParam;
  }
};

// 加载用户数据
const loadUserData = async () => {
  // const mockData: any = await gmtTaskinfo(id.value);
  // const scriptData: any = await gmtScriptinfo(route.params.scriptId);
  try {
    // 使用Promise.all并行请求两个接口
    const [mockData, scriptData] = await Promise.all([
      gmtTaskinfo(id.value) as any,
      gmtScriptinfo(route.params.scriptId) as any,
    ]);
    // 处理获取到的数据
    scriptDataValue.value = scriptData;
    scriptValue.value = scriptData.scriptId;
    mockData.taskParam = JSON.parse(mockData.taskParam);
    Object.assign(form, mockData);
    // 可以将数据赋值给响应式变量
    // taskInfo.value = mockData;
    // scriptInfo.value = scriptData;
  } catch (error) {
    // 处理错误
    console.error("请求失败:", error);
  }
};

//运行代码
const runCode = async () => {
  await dynamicsNatRef.value.saveData();
};

// 提交表单
const submitForm = async () => {
  if (route.params.id != "add") {
    await dynamicsNatRef.value.saveData();
    try {
      await formRef.value.validate();
      await gmtTaskinfoUpdate({
        taskId: form.taskId,
        taskName: form.taskName,
        taskParam: form.taskParam,
      });
      // API请求
    } catch (error) {
      console.log("表单验证失败", error);
    }
  } else {
    await gmtTaskinfosave({
      taskName: form.taskName,
      taskParam: form.taskParam,
      scriptId: scriptValue.value,
    });
  }
  router.push({
    name: "GMT-task",
  });
};

// 运行动态任务
const runForm = async () => {
  // try {
  //   await formRef.value.validate();
  //   if (route.params.id != "add") {
  //     await gmtTaskinfoUpdate({
  //       resId: form.resId,
  //       resName: form.resName,
  //       resDes: form.resDes,
  //       resType: form.resType,
  //       dynamic: form.dynamic,
  //     });
  //   }
  //   if (form.dynamic == 1) {
  //     await dynamicsNatRef.value.saveData();
  //   } else {
  //     await gmtTaskinfosave({
  //       resId: form.resId,
  //       resText: form.resText,
  //     });
  //   }
  //   loadUserData();
  // } catch (error) {
  //   console.log("表单验证失败", error);
  // }
};

const handleClick = (id) => {
  console.log("id", id);
  // id.value = id;
  form.resId = id;
};

// 取消编辑
const cancel = () => {
  router.push({
    name: "office-naturalRes",
  });
};

//代码编辑器
</script>

<style scoped>
.user-edit-container {
  padding: 20px;
}
.button-row {
  display: flex;
  justify-content: flex-end; /* 右对齐 */
  width: 100%;
  margin: 10px 0;
}

.button-row button {
  padding: 6px 12px;
  background: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
</style>
